package site.wanjiahao.util;


import java.util.Objects;

public class Hash {

    public static void main(String[] args) {
        System.out.println(hashCode(12.5f));
    }


    // int数据直接返回
    public static int hashCode(int value) {
        return value;
    }

    // float，占4位，与int一样
    public static int hashCode(float value) {
        return Float.floatToIntBits(value);
    }

    // long double
    public static int hashCode(long value) {
        // 高32位和第32位异或，返回后32位
        return (int) (value ^ (value >>> 32));
    }

    // long double
    public static int hashCode(double value) {
        // 高32位和第32位异或，返回后32位
        long bits = Double.doubleToLongBits(value);
        return (int) (bits ^ (bits >>> 32));
    }

    // 字符串计算
    // hashCode = hashCode * 31 + str.charAt(i); JVM 优化为  (hashCode << 5) - hashCode + c
    public static int hashCode(String str) {
        int hashCode = 0;
        for (int i = 0; i < str.length(); i++) {
            hashCode = hashCode * 31 + str.charAt(i);
        }
        return hashCode;
    }

    static class Person {

        private int age;

        private float height;

        private String name;


        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (o == null || getClass() != o.getClass()) return false;
            Person person = (Person) o;
            return age == person.age && Float.compare(person.height, height) == 0 && Objects.equals(name, person.name);
        }

        @Override
        public int hashCode() {
            int hashCode = Integer.hashCode(age);
            hashCode = hashCode * 31 + Float.hashCode(height);
            hashCode = hashCode * 31 + name.hashCode();
            return hashCode;
        }
    }


}
